﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;


namespace Dragoon
{
  public class SkyDome : EffectComponent, IViewDrawable
  {
    PerlinNoise _noise;
    Model skyDome;
    ICamera camera;

    public SkyDome(Game game, ICamera cam, PerlinNoise noise)
      : base(game)
    {
      camera = cam;
      _noise = noise;
    }

    protected override void LoadContent()
    {
      skyDome = Game.Content.Load<Model>("dome");
      skyDome.Meshes[0].MeshParts[0].Effect = _effect.Clone(GraphicsDevice);
      base.LoadContent();
    }

    public void Draw(Matrix viewMatrix)
    {
      GraphicsDevice.RenderState.DepthBufferWriteEnable = false;

      Matrix[] modelTransforms = new Matrix[skyDome.Bones.Count];
      skyDome.CopyAbsoluteBoneTransformsTo(modelTransforms);

      Matrix wMatrix = Matrix.CreateTranslation(0, -0.30f, 0)
                     * Matrix.CreateScale(300)
                     * Matrix.CreateTranslation(camera.Position);
      foreach (ModelMesh mesh in skyDome.Meshes)
      {
        foreach (Effect currentEffect in mesh.Effects)
        {
          Matrix worldMatrix = modelTransforms[mesh.ParentBone.Index] * wMatrix;
          currentEffect.CurrentTechnique = currentEffect.Techniques["SkyDome"];
          currentEffect.Parameters["xWorld"].SetValue(worldMatrix);
          currentEffect.Parameters["xView"].SetValue(viewMatrix);
          currentEffect.Parameters["xProjection"].SetValue(camera.ProjectionMatrix);
          currentEffect.Parameters["xTexture"].SetValue(_noise.Texture);
          currentEffect.Parameters["xEnableLighting"].SetValue(false);
        }
        mesh.Draw();
      }
      GraphicsDevice.RenderState.DepthBufferWriteEnable = true;

    }

    public override void Draw(GameTime gameTime)
    {
      Draw(camera.ViewMatrix);
    }

  }
}